package com.sduept.nwld.dataview.controller.core;

import com.sduept.cim.ledger.enums.ManagementUnitEnum;
import com.sduept.cim.ledger.excetpion.ManagementUnitException;
import com.sduept.cim.ledger.manager.SubstationLedgerManager;
import com.sduept.cim.ledger.model.ManagementUnitDict;
import com.sduept.cim.ledger.model.SubstationLedger;
import com.sduept.cim.ledger.services.ManagementUnitService;
import com.sduept.cim.model.core.Substation;
import com.sduept.bigdata.web.jsf.controller.AbstractController;
import com.sduept.bigdata.weather.map.MapDataCache;
import com.sduept.nwld.dataserver.manager.cim.CimManager;
import com.sduept.nwld.dataserver.util.LibTreeNode;
import org.apache.commons.lang3.StringUtils;
import org.primefaces.PrimeFaces;
import org.primefaces.event.NodeExpandEvent;
import org.primefaces.event.NodeSelectEvent;
import org.primefaces.event.NodeUnselectEvent;
import org.primefaces.event.SelectEvent;
import org.primefaces.model.DefaultTreeNode;
import org.primefaces.model.TreeNode;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.PostConstruct;
import javax.faces.view.ViewScoped;
import javax.inject.Named;
import java.util.*;

/**
 * @author huangyu
 * @Date 2019年9月27日
 */
@Named
@ViewScoped
public class SubstationGroupByOpSubstationSelectorController extends AbstractController {

	private static final long serialVersionUID = -4260761157798531980L;
	
	@Autowired
	private ManagementUnitService unitService;
	@Autowired
	private SubstationLedgerManager stationLedgerM;

	@Autowired
	private CimManager cimM;
	@Autowired
	private MapDataCache cc;

	/**
	 * 快速筛选变电站
	 */
	private String stationSearch;
	private TreeNode selectedNode;
	
	
	private TreeNode stationRoot; // 变电站选择树
	/**
	 * 传递的已选择变电站id
	 */
	private String[] selectedStations;
	/**
	 * 所有的运维单位
	 */
	private List<ManagementUnitDict> allMaintenance;
	/**
	 * 所有的检修范围,<id,ManagementUnitDict>
	 */
	private Map<String,ManagementUnitDict> maintenanceScopesMap = new HashMap<String, ManagementUnitDict>();
	private Map<String, Substation> stationMap = new HashMap<String, Substation>();
	private String selectedVol = "500";
	private TreeNode[] selectedNodes; // 多选择
	private List<Substation> selects = new ArrayList<Substation>();
	
	@PostConstruct
	public void init() {
		selectedStations = getParameters("stationIds");
		stationMap = cc.getStationid_map();
		genMaintenanceScopesMap();
		try {
			allMaintenance = unitService.getAllMaintenanceManagements();
			initStationTree();
		} catch (ManagementUnitException e) {
			e.printStackTrace();
			addErrorMessage("获取所有的运维单位出错");
		}
	}

	/**
	 * 获取检修范围，封装成Map<id,ManagementUnitDict>
	 */
	private void genMaintenanceScopesMap() {
		try {
			List<ManagementUnitDict> allMaintenanceScopes = unitService.getAllMaintenanceScopes();
			for (ManagementUnitDict unit : allMaintenanceScopes) {
				maintenanceScopesMap.put(unit.getId(), unit);
			}
		} catch (ManagementUnitException e) {
			e.printStackTrace();
			addErrorMessage("获取全部的检修范围出错");
		}
	}
	
	private void initStationTree() {
		stationRoot = new LibTreeNode("Root", null);
		try {
			String rootName = unitService.getManagementUnitRoot();
			if(StringUtils.isEmpty(rootName)) {
				rootName = "南方电网";
			}
			// 组织机构的根节点，即南方电网
			LibTreeNode rootNode = new LibTreeNode("root", rootName, stationRoot);
			// 获取调度单位第一级（实际上为检修范围，仅作为分组显示使用）
			List<ManagementUnitDict> firstLevelChilds = getUnitsByPidFromList(null);
			for (ManagementUnitDict unit : firstLevelChilds) {
				recursionGenChildNode(unit, rootNode);
			}
			rootNode.setExpanded(true);
		} catch (ManagementUnitException e) {
			e.printStackTrace();
			addErrorMessage("获取部门根节点失败");
		}
		stationSearch = null;
	}
	
	/**
	 * 递归查找下一级节点，
	 * @param dept
	 * @param treeNode
	 */
	private void recursionGenChildNode(ManagementUnitDict unit, TreeNode rootNode) {
		LibTreeNode treeNode = new LibTreeNode("maintenanceUnit", unit, rootNode);
		if(unit.getUnitType() == ManagementUnitEnum.MAINTENANCE_MANAGEMENT) {
			// 当类型为运维时，查找其下的变电站
			// 获取该部门下的变电站
			List<SubstationLedger> stationLedgers = stationLedgerM.querySubstationByVoltageAndMaintenanceUnit(selectedVol, unit);
			for (SubstationLedger ledger : stationLedgers) {
				Substation station = stationMap.get(ledger.getCimId());
				LibTreeNode node = new LibTreeNode("station", station, treeNode);
				if(selectedStations==null) {
					continue;
				}
				for (int i=0;i<selectedStations.length;i++) {
					if(station.getId().equals(selectedStations[i])) {
						node.setSelected(true);
					}
				}
			}
		}
		// 获取该部门下的子部门
		List<ManagementUnitDict> childs = getUnitsByPidFromList(unit.getId());
		for (ManagementUnitDict dict : childs) {
			recursionGenChildNode(dict, treeNode);
		}
	}
	/**
	 * 根据pid，从allMaintenance中获取pid符合条件的记录
	 * pid=null,从所有的运维单位中，获取一级单位，即如果某记录的父单位类型为检修范围，则该父部门设为运维单位的一级单位
	 * @param pid
	 * @return 
	 */
	private List<ManagementUnitDict> getUnitsByPidFromList(String pid) {
		List<ManagementUnitDict> result = new ArrayList<ManagementUnitDict>();
		if(null == pid) {
			Set<ManagementUnitDict> units = new HashSet<ManagementUnitDict>();
			for (ManagementUnitDict unit : allMaintenance) {
				if(maintenanceScopesMap.containsKey(unit.getPid())) {
					units.add(maintenanceScopesMap.get(unit.getPid()));
				}
			}
			result.addAll(units);
		} else {
			for (ManagementUnitDict unit : allMaintenance) {
				if(pid.equals(unit.getPid())) {
					result.add(unit);
				}
			}
		}
		sort(result);
		return result;
	}
	
	/**
	 * 将ManagementUnitDict按ordered从高到低排序
	 * @param List<ManagementUnitDict>
	 */
	private void sort(List<ManagementUnitDict> list) {
		Collections.sort(list,new Comparator<ManagementUnitDict> () {
			@Override
			public int compare(ManagementUnitDict o1, ManagementUnitDict o2) {
				return o2.getOrdered()-o1.getOrdered();
			}
		});
	}

	/**
	 * 选择变电站后，重新构造树
	 */
	public void changeVoltage(){
		if("0".equals(selectedVol)) {
			selectedVol = null;
		}
		initStationTree();
	}
	
	/**
	 * 确定选择变电站后
	 */
	public void onSubstationSelected() {
		if(null == selectedNodes) {
			PrimeFaces.current().dialog().closeDynamic(selects);
			return;
		}
		selects.clear();
		for(TreeNode tn : selectedNodes){
			if("maintenanceUnit".equals(tn.getType())) {
				// 选中了某个部门，即选中了部门下的所有变电站
				// 根据电压等级、部门获取变电站
				ManagementUnitDict dept = (ManagementUnitDict) tn.getData();
				List<SubstationLedger> stationLedgers = stationLedgerM.querySubstationByVoltageAndMaintenanceUnit(selectedVol, dept);
				for (SubstationLedger ledger : stationLedgers) {
					Substation station = stationMap.get(ledger.getCimId());
					if(!selects.contains(station)) {
						selects.add(station);
					}
				}
			} else if ("station".equals(tn.getType())) {
				Substation station = (Substation) tn.getData();
				if(!selects.contains(station)) {
					selects.add(station);
				}
			}
		}
		PrimeFaces.current().dialog().closeDynamic(selects);
	}

	public void onNodeExpand(NodeExpandEvent event) {
		
	}
	
	public void onStationNodeSelect(NodeSelectEvent event) {
		
	}
	
	public void onStationNodeUnSelect(NodeUnselectEvent event) {
		
	}
	
	/**
	 * 变电站选择树增加快速筛选功能
	 * @param event
	 */
	public void reGenStationTree(SelectEvent event) {
		Object item = event.getObject();
		if (null != item) {
			stationRoot = new DefaultTreeNode();
			List<Substation> stations = cimM.getStationByName(item.toString());
			for (Substation s : stations) {
				new LibTreeNode("station", s, stationRoot);
			}
		}
	}
	/**
	 * 清除快速筛选信息
	 */
	public void refreshStationTree() {
		stationSearch = null;
		setSelectedNode(null);
		initStationTree();
	}
	
	public void onOneSubstationSelect() {
		if (selectedNode != null && "station".equals(selectedNode.getType())) {
			Substation select = (Substation) selectedNode.getData();
			PrimeFaces.current().dialog().closeDynamic(select);
		} else {
			alertErrorMessage("请选择变电站");
		}
	}

	/**
	 * 选中树节点
	 * @param event
	 */
	public void onNodeSelect(NodeSelectEvent event) {
		if ("station".equals(event.getTreeNode().getType())) {
			selectedNode = event.getTreeNode();
		}
	}

	public String getSelectedVol() {
		return selectedVol;
	}

	public List<Substation> getSelects() {
		return selects;
	}

	public void setSelectedVol(String selectedVol) {
		this.selectedVol = selectedVol;
	}

	public void setSelects(List<Substation> selects) {
		this.selects = selects;
	}

	public TreeNode getStationRoot() {
		return stationRoot;
	}

	public void setStationRoot(TreeNode stationRoot) {
		this.stationRoot = stationRoot;
	}

	public TreeNode[] getSelectedNodes() {
		return selectedNodes;
	}

	public void setSelectedNodes(TreeNode[] selectedNodes) {
		this.selectedNodes = selectedNodes;
	}

	public String getStationSearch() {
		return stationSearch;
	}

	public void setStationSearch(String stationSearch) {
		this.stationSearch = stationSearch;
	}

	public TreeNode getSelectedNode() {
		return selectedNode;
	}

	public void setSelectedNode(TreeNode selectedNode) {
		this.selectedNode = selectedNode;
	}
}
